﻿using Aliyun.OSS;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace Adnc.Application.Shared.AliyunAudit
{
    public class OSS
    {
        /// <summary>
        /// 获取阿里云 accessKeyId
        /// </summary>
        private string accessKeyId { get; set; }
        /// <summary>
        /// 获取阿里云 accessKeySecret
        /// </summary>
        private string accessKeySecret { get; set; }

        /// <summary>
        /// OSSUrl
        /// </summary>
        private string OSSUrl { get; set; }

        public OSS(AliyunOptions option)
        {
            accessKeyId = option.AccessKeyId;
            accessKeySecret = option.AccessKeySecret;
            OSSUrl = option.OSSUrl;
        }

        /// <summary>
        /// OSS签名
        /// </summary>
        /// <param name="dir">用户上传文件时指定的前缀</param>
        /// <returns></returns>
        public OssSign OssSign(string dir = "")
        {
            OssClient client = new OssClient(OSSUrl, accessKeyId, accessKeySecret);

            DateTime ex = DateTime.Now.AddSeconds(60);

            PolicyConditions policyConds = new PolicyConditions();
            policyConds.AddConditionItem(PolicyConditions.CondContentLengthRange, 0L, 1048576000L);
            policyConds.AddConditionItem(MatchMode.StartWith, PolicyConditions.CondKey, dir);

            String postPolicy = client.GeneratePostPolicy(ex, policyConds);
            byte[] binaryData = Encoding.UTF8.GetBytes(postPolicy);
            String policy = Convert.ToBase64String(binaryData);

            var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(accessKeySecret));
            var hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(policy));
            var Signature = Convert.ToBase64String(hashBytes);
            return new OssSign
            {
                AccessKeyId = accessKeyId,
                Policy = policy,
                Signature = Signature,
                Dir = dir,
                Host = OSSUrl,
                Expire = ex.ToEpochTimeSpan().Seconds
            };
        }

    }


    public class OssSign
    {
        /// <summary>
        /// 
        /// </summary>
        public string AccessKeyId { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string Policy { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string Signature { get; set; }
        /// <summary>
        /// 路径
        /// </summary>
        public string Dir { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string Host { get; set; }
        /// <summary>
        /// 时间戳
        /// </summary>
        public int Expire { get; set; }
    }
}
